﻿using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Models;
using MultiDAQ_Analysis.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using BackgroundMeasurementResult = MultiDAQ_Analysis.Model.BackgroundMeasurementResult;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// 本底测量用户控件（工作源测量）
    /// 功能：执行本底测量并保存结果，为其他测量提供本底数据
    /// </summary>
    public partial class UcBaseMeasurement : UserControl
    {
        #region 字段定义

        private int channelCount = AppConfig.ChannelCount;
        private List<ChannelData> channelDataList;

        // 添加控件引用字段
        private UITextBox txtMeasurementCount;
        private UITextBox txtMeasurementTime;
        // 新增：多次测量跟踪
        private int currentMeasurementCycle = 0;
        private int totalMeasurementCycles = 0;
        private Dictionary<int, List<(double alpha, double beta)>> measurementHistory =
            new Dictionary<int, List<(double alpha, double beta)>>();

        protected virtual string MeasurementType { get; set; } = "Background";
        #endregion
        #region 测量结果显示
        // 测量类型显示名称映射
        protected static readonly Dictionary<string, string> MeasurementTypeDisplayNames = new Dictionary<string, string>
{
    {"Background", "本底测量"},
    {"WorkingSourceEfficiency", "工作源效率测量"},
    {"StandardSourceEfficiency", "标准源效率测量"},
    {"WaterSample", "水样品测量"},
    {"BioSample", "生物样品测量"},
    {"GasSample", "气体样品测量"},
    {"EnvSample", "环境样品测量"}
};
        // ================================
        // 3. 通用化的查看最新结果方法
        // ================================

        /// <summary>
        /// 查看最新结果按钮点击事件 - 通用版本
        /// 根据组件的测量类型显示对应的最新多轮测量结果
        /// </summary>
        private async void BtnViewLatestResult_Click(object sender, EventArgs e)
        {
            string originalText = "查看最新结果"; // 在方法开始处
            try
            {
                var clickedButton = sender as UIButton;
                string measurementType = clickedButton?.Tag?.ToString() ?? MeasurementType;
                string displayName = GetMeasurementTypeDisplayName(measurementType);

                // 显示加载提示
                originalText = clickedButton?.Text ?? "查看最新结果";
                if (clickedButton != null)
                {
                    clickedButton.Enabled = false;
                    clickedButton.Text = "加载中...";
                }

                // 查找该类型的最新测量数据
                var latestMeasurementData = await FindLatestMeasurementByType(measurementType);

                if (latestMeasurementData == null)
                {
                    UIMessageBox.ShowWarning($"暂无{displayName}结果！\n请先完成{displayName}后再查看结果。");
                    return;
                }

                // 打开MultiRoundResultForm显示结果
                var resultForm = new MultiRoundResultForm(latestMeasurementData);
                resultForm.ShowDialog(this);

                System.Diagnostics.Debug.WriteLine($"已显示{displayName}最新测量结果，测量时间：{latestMeasurementData.StartTime:yyyy-MM-dd HH:mm:ss}");
            }
            catch (Exception ex)
            {
                string displayName = GetMeasurementTypeDisplayName(MeasurementType);
                UIMessageBox.ShowError($"查看{displayName}最新结果失败：{ex.Message}");
                System.Diagnostics.Debug.WriteLine($"查看{displayName}最新结果失败: {ex.Message}");
            }
            finally
            {
                // 恢复按钮状态
                var clickedButton = sender as UIButton;
                if (clickedButton != null)
                {
                    clickedButton.Enabled = true;
                    clickedButton.Text = originalText;
                }
            }
        }

        /// <summary>
        /// 根据测量类型查找最新的测量数据 - 通用方法
        /// </summary>
        /// <param name="measurementType">测量类型（如"WaterSample", "BioSample"等）</param>
        /// <returns>最新的测量数据，如果不存在返回null</returns>
        /// <summary>
        /// 根据测量类型查找最新的测量数据 - 修复版本，合并所有通道数据
        /// </summary>
        /// <param name="measurementType">测量类型（如"WaterSample", "BioSample"等）</param>
        /// <returns>最新的测量数据，如果不存在返回null</returns>
        private async Task<MultiRoundMeasurementData> FindLatestMeasurementByType(string measurementType)
        {
            try
            {
                DateTime latestTime = DateTime.MinValue;
                string latestMeasurementId = null;
                var channelDataList = new List<MultiRoundMeasurementData>();

                // 第一轮：找到最新的测量时间和ID
                for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                {
                    try
                    {
                        var channelMeasurementData = await ChannelBasedJsonDataManager.GetChannelMeasurementAsync(channelIndex, measurementType);

                        if (channelMeasurementData != null && channelMeasurementData.StartTime > latestTime)
                        {
                            latestTime = channelMeasurementData.StartTime;
                            latestMeasurementId = channelMeasurementData.MeasurementId;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"检查通道 {channelIndex + 1} {measurementType} 数据时出错: {ex.Message}");
                    }
                }

                if (latestTime == DateTime.MinValue || string.IsNullOrEmpty(latestMeasurementId))
                {
                    System.Diagnostics.Debug.WriteLine($"未找到任何{measurementType}测量数据");
                    return null;
                }

                // 第二轮：收集所有具有相同测量ID的通道数据
                MultiRoundMeasurementData mergedData = null;
                var allChannelResults = new Dictionary<int, ChannelMultiRoundResult>();

                for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                {
                    try
                    {
                        var channelMeasurementData = await ChannelBasedJsonDataManager.GetChannelMeasurementAsync(channelIndex, measurementType);

                        // 只合并具有相同测量ID的数据（同一次测量的不同通道）
                        if (channelMeasurementData != null &&
                            channelMeasurementData.MeasurementId == latestMeasurementId)
                        {
                            // 第一次找到时，初始化合并数据的基础结构
                            if (mergedData == null)
                            {
                                mergedData = new MultiRoundMeasurementData
                                {
                                    MeasurementId = channelMeasurementData.MeasurementId,
                                    MeasurementType = channelMeasurementData.MeasurementType,
                                    StartTime = channelMeasurementData.StartTime,
                                    EndTime = channelMeasurementData.EndTime,
                                    TotalRounds = channelMeasurementData.TotalRounds,
                                    MeasurementTimeMinutes = channelMeasurementData.MeasurementTimeMinutes,
                                    Parameters = channelMeasurementData.Parameters,
                                    CalculationContext = channelMeasurementData.CalculationContext,
                                    ChannelResults = new Dictionary<int, ChannelMultiRoundResult>()
                                };
                            }

                            // 合并该通道的结果
                            foreach (var channelResult in channelMeasurementData.ChannelResults)
                            {
                                allChannelResults[channelResult.Key] = channelResult.Value;
                            }

                            System.Diagnostics.Debug.WriteLine($"已合并通道 {channelIndex + 1} 的{measurementType}数据");
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"合并通道 {channelIndex + 1} {measurementType} 数据时出错: {ex.Message}");
                    }
                }

                if (mergedData != null && allChannelResults.Count > 0)
                {
                    mergedData.ChannelResults = allChannelResults;

                    string displayName = GetMeasurementTypeDisplayName(measurementType);
                    System.Diagnostics.Debug.WriteLine($"找到最新{displayName}数据：");
                    System.Diagnostics.Debug.WriteLine($"  测量时间: {mergedData.StartTime:yyyy-MM-dd HH:mm:ss} - {mergedData.EndTime:yyyy-MM-dd HH:mm:ss}");
                    System.Diagnostics.Debug.WriteLine($"  总轮数: {mergedData.TotalRounds}");
                    System.Diagnostics.Debug.WriteLine($"  参与通道: {mergedData.ChannelResults.Count} 个");
                    System.Diagnostics.Debug.WriteLine($"  测量ID: {mergedData.MeasurementId}");

                    return mergedData;
                }

                System.Diagnostics.Debug.WriteLine($"未找到有效的{measurementType}合并数据");
                return null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"查找最新{measurementType}测量数据失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 获取测量类型的显示名称
        /// </summary>
        /// <param name="measurementType">英文测量类型</param>
        /// <returns>中文显示名称</returns>
        private string GetMeasurementTypeDisplayName(string measurementType)
        {
            return MeasurementTypeDisplayNames.ContainsKey(measurementType)
                ? MeasurementTypeDisplayNames[measurementType]
                : measurementType;
        }
        #endregion
        #region 构造函数和初始化

        public UcBaseMeasurement()
        {
            InitializeComponent();
            LoadChannelData();                  // 加载通道数据
            ConfigureOuterLayoutRowStyles();    // 配置布局

            // 避免构建时的布局抖动
            this.SuspendLayout();
            BuildDuration();
            BuildButtons();
            this.ResumeLayout(true);

            LoadMeasurementSettings();         // 加载测量设置
        }

        /// <summary>
        /// 加载通道数据
        /// </summary>
        private void LoadChannelData()
        {
            try
            {
                channelDataList = ChannelDataManager.LoadAllChannelData();

                // 确保有足够的通道数据
                while (channelDataList.Count < channelCount)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = channelDataList.Count });
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载通道数据失败：{ex.Message}");
                // 初始化默认数据
                channelDataList = new List<ChannelData>();
                for (int i = 0; i < channelCount; i++)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = i });
                }
            }
        }

        ///// <summary>
        ///// 加载测量设置到界面
        ///// </summary>
        //private void LoadMeasurementSettings()
        //{
        //    try
        //    {
        //        if (channelDataList.Count > 0)
        //        {
        //            var workCondition = channelDataList[0].WorkConditions;
        //            var txtCount = this.Controls.Find("txtMeasurementCount", true).FirstOrDefault() as UITextBox;
        //            var txtTime = this.Controls.Find("txtMeasurementTime", true).FirstOrDefault() as UITextBox;

        //            if (txtCount != null)
        //                txtCount.Text = workCondition.MeasurementCycle.ToString();
        //            if (txtTime != null)
        //                txtTime.Text = workCondition.MeasurementTime.ToString("0.#");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine($"加载测量设置失败: {ex.Message}");
        //    }
        //}

        /// <summary>
        /// 配置外部布局行样式
        /// 确保第 6、8 行为 AutoSize，其余行也 AutoSize
        /// </summary>
        private void ConfigureOuterLayoutRowStyles()
        {
            if (outerLayout == null) return;

            outerLayout.SuspendLayout();
            outerLayout.AutoSize = true;
            outerLayout.AutoSizeMode = AutoSizeMode.GrowAndShrink;

            // 确保至少有 9 行（索引 0..8）
            if (outerLayout.RowCount < 9) outerLayout.RowCount = 9;

            // 清空并重建 RowStyles
            outerLayout.RowStyles.Clear();
            for (int i = 0; i < outerLayout.RowCount; i++)
            {
                outerLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            }

            // 明确强调第 6、8 行是 AutoSize
            outerLayout.RowStyles[6].SizeType = SizeType.AutoSize;
            outerLayout.RowStyles[8].SizeType = SizeType.AutoSize;

            outerLayout.ResumeLayout(true);
        }

        #endregion

        #region 界面构建方法

        /// <summary>
        /// 构建按钮区域
        /// </summary>
        private void BuildButtons()
        {
            panelButtons.AutoSize = true;
            panelButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            panelButtons.Dock = DockStyle.Top;
            panelButtons.Padding = new Padding(0);
            panelButtons.Margin = new Padding(16, 8, 16, 0);

            panelButtons.Controls.Clear();

            var panel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = false,
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            var btnStartMeasurement = new UIButton
            {
                Text = "开始测量",
                Width = 110,
                Height = 36,
                Margin = new Padding(60, 0, 0, 0)
            };
            btnStartMeasurement.Click += BtnStartMeasurement_Click;

            var btnCancel = new UIButton
            {
                Text = "取消",
                Width = 110,
                Height = 36,
                Margin = new Padding(32, 0, 0, 0)
            };
            btnCancel.Click += BtnCancel_Click;

            // 查看最新结果按钮
            var btnViewLatestResult = new UIButton
            {
                Text = "查看最新结果",
                Width = 130,
                Height = 36,
                Margin = new Padding(20, 0, 0, 0),
                FillColor = Color.FromArgb(103, 194, 58),
                ForeColor = Color.White,
                Tag = MeasurementType // 使用Tag存储测量类型
            };
            btnViewLatestResult.Click += BtnViewLatestResult_Click;
            panel.Controls.Add(btnViewLatestResult);

            panel.Controls.Add(btnStartMeasurement);
            panel.Controls.Add(btnCancel);

            panelButtons.Controls.Add(panel);
            this.outerLayout.Controls.Add(panelButtons, 0, 8);
        }

        #endregion

        #region 事件处理和数据保存


        /// <summary>
        /// 刷新通道数据和界面显示
        /// </summary>
        public void RefreshData()
        {
            try
            {
                LoadChannelData();
                LoadMeasurementSettings(); // 重新加载测量设置到界面

                // 如果需要，可以添加其他界面元素的刷新逻辑
                System.Diagnostics.Debug.WriteLine("通道数据已刷新");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"刷新数据失败：{ex.Message}");
            }
        }

        public event Action<int, int> OnMeasurementStarted;

        /// <summary>
        /// 开始测量按钮点击事件
        /// 验证参数并保存测量配置，然后开始本底测量
        /// </summary>
        private void BtnStartMeasurement_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取测量参数
                var txtMeasurementCount = this.Controls.Find("txtMeasurementCount", true).FirstOrDefault() as UITextBox;
                var txtMeasurementTime = this.Controls.Find("txtMeasurementTime", true).FirstOrDefault() as UITextBox;

                if (txtMeasurementCount == null || txtMeasurementTime == null)
                {
                    UIMessageBox.ShowError("找不到输入框控件。");
                    return;
                }

                // 验证输入参数
                if (!int.TryParse(txtMeasurementCount.Text, out int measurementCount) ||
                    !int.TryParse(txtMeasurementTime.Text, out int measurementTime))
                {
                    UIMessageBox.ShowError("请输入有效的数字。");
                    return;
                }

                if (measurementCount <= 0 || measurementTime <= 0)
                {
                    UIMessageBox.ShowError("测量次数和测量时间必须大于0。");
                    return;
                }

                // === 新增：保存工作条件到配置文件（实现双向绑定）===
                bool workConditionSaved = SaveWorkConditionToConfig();
                if (!workConditionSaved)
                {
                    var result = MessageBox.Show("工作条件保存失败，是否继续进行测量？",
                                               "保存提示",
                                               MessageBoxButtons.YesNo,
                                               MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                // 保存测量配置
                if (!SaveMeasurementSettings(measurementCount, measurementTime))
                {
                    return; // 保存失败，不继续执行
                }

                // 初始化多次测量状态
                totalMeasurementCycles = measurementCount;
                currentMeasurementCycle = 0;
                measurementHistory.Clear();

                // 触发测量开始事件
                OnMeasurementStarted?.Invoke(measurementCount, measurementTime);

                string successMessage = $"开始本底测量：{measurementCount} 次测量，每次 {measurementTime} 分钟";
                if (workConditionSaved)
                {
                    successMessage += "\n工作条件已保存到配置文件";
                }

                UIMessageBox.ShowSuccess(successMessage);

                this.Parent?.Hide();
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"启动本底测量时发生错误：{ex.Message}");
                ResetMeasurementState();
            }
        }
        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Parent?.Hide();
        }

        /// <summary>
        /// 保存工作条件数据到配置文件（实现双向绑定）
        /// 从界面控件读取数据并保存到配置文件
        /// </summary>
        private bool SaveWorkConditionToConfig()
        {
            try
            {
                // 保存测量设置（所有通道使用相同值）
                if (txtMeasurementCount != null &&
                    int.TryParse(txtMeasurementCount.Text, out int measurementCycle))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementCycle = measurementCycle;
                    }
                }

                if (txtMeasurementTime != null &&
                    double.TryParse(txtMeasurementTime.Text, out double measurementTime))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementTime = measurementTime;
                    }
                }

                // 保存到文件
                bool saved = ChannelDataManager.SaveAllChannelData(channelDataList);

                if (saved && AppConfig.LogPrint == 1)
                {
                    Console.WriteLine("[本底测量] 工作条件已保存到配置文件");
                }

                return saved;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[本底测量] 保存工作条件失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 保存测量配置到通道数据
        /// </summary>
        /// <param name="measurementCount">测量次数</param>
        /// <param name="measurementTime">测量时间</param>
        /// <returns>是否保存成功</returns>
        private bool SaveMeasurementSettings(int measurementCount, double measurementTime)
        {
            try
            {
                // 保存到所有通道
                for (int i = 0; i < channelCount; i++)
                {
                    var channelData = channelDataList[i];
                    channelData.WorkConditions.MeasurementCycle = measurementCount;
                    channelData.WorkConditions.MeasurementTime = measurementTime;
                    channelData.LastModified = DateTime.Now;

                    // 保存到JSON文件
                    ChannelDataManager.SaveChannelData(i, channelData);
                }

                System.Diagnostics.Debug.WriteLine($"本底测量配置已保存：次数 {measurementCount}，时间 {measurementTime} 分钟");
                return true;
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"保存测量配置失败：{ex.Message}");
                return false;
            }
        }

        #endregion

        #region 静态辅助方法

        /// <summary>
        /// 从通道数据中读取本底测量结果
        /// </summary>
        /// <param name="channelIndex">通道索引</param>
        /// <returns>本底测量结果，如果不存在返回null</returns>
        public static BackgroundMeasurementResult GetBackgroundResult(int channelIndex)
        {
            try
            {
                var channelData = ChannelDataManager.LoadChannelData(channelIndex);
                return channelData.MeasurementResults?.BackgroundMeasurement;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取通道 {channelIndex + 1} 本底测量结果失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 检查指定通道是否有本底测量结果
        /// </summary>
        /// <param name="channelIndex">通道索引</param>
        /// <returns>是否有结果</returns>
        public static bool HasBackgroundResult(int channelIndex)
        {
            var result = GetBackgroundResult(channelIndex);
            return result != null && result.MeasurementTime != default(DateTime);
        }

        /// <summary>
        /// 获取所有通道的本底数据
        /// </summary>
        /// <returns>各通道本底数据字典</returns>
        public static Dictionary<int, (double alphaBackground, double betaBackground)> GetAllBackgroundData()
        {
            var result = new Dictionary<int, (double alphaBackground, double betaBackground)>();
            int channelCount = AppConfig.ChannelCount;

            for (int i = 0; i < channelCount; i++)
            {
                var backgroundResult = GetBackgroundResult(i);
                if (backgroundResult != null)
                {
                    result[i] = (backgroundResult.AlphaBackground, backgroundResult.BetaBackground);
                }
            }

            return result;
        }

        #endregion

        #region 数据刷新
        /// <summary>
        /// 构建测量时长区域
        /// </summary>
        private void BuildDuration()
        {
            var group = new UIGroupBox
            {
                Text = "测量时长",
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                Padding = new Padding(12),
                Margin = new Padding(16, 8, 16, 0)
            };

            var table = new TableLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                ColumnCount = 4,
                RowCount = 1,
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            table.ColumnStyles.Clear();
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));

            table.RowStyles.Clear();
            table.RowStyles.Add(new RowStyle(SizeType.AutoSize));

            var lblCount = new UILabel
            {
                Text = "测量次数",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };

            // 保存控件引用
            txtMeasurementCount = new UITextBox
            {
                Name = "txtMeasurementCount",
                Text = "1",
                Width = 80,
                Margin = new Padding(0, 2, 24, 2),
                Anchor = AnchorStyles.Left,
                Enabled = true,
                ReadOnly = false,
                BackColor = Color.White,
            };

            var lblTime = new UILabel
            {
                Text = "测量时间(min)",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };

            // 保存控件引用
            txtMeasurementTime = new UITextBox
            {
                Name = "txtMeasurementTime",
                Text = "5",
                Width = 80,
                Margin = new Padding(0, 2, 0, 2),
                Enabled = true,
                ReadOnly = false,
                BackColor = Color.White,
                Anchor = AnchorStyles.Left
            };

            table.Controls.Add(lblCount, 0, 0);
            table.Controls.Add(txtMeasurementCount, 1, 0);
            table.Controls.Add(lblTime, 2, 0);
            table.Controls.Add(txtMeasurementTime, 3, 0);

            group.Controls.Add(table);
            this.outerLayout.Controls.Add(group, 0, 6);

            group.Height = group.PreferredSize.Height;
        }

        /// <summary>
        /// 加载测量设置到界面
        /// </summary>
        private void LoadMeasurementSettings()
        {
            try
            {
                if (channelDataList.Count > 0)
                {
                    var workCondition = channelDataList[0].WorkConditions;

                    // 直接使用保存的控件引用
                    if (txtMeasurementCount != null)
                        txtMeasurementCount.Text = workCondition.MeasurementCycle.ToString();

                    if (txtMeasurementTime != null)
                        txtMeasurementTime.Text = workCondition.MeasurementTime.ToString("0.#");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载测量设置失败: {ex.Message}");
            }
        }
        #endregion

        #region 数据计算

        /// <summary>
        /// 处理本底测量完成事件
        /// 当实际本底测量完成时调用此方法保存本底数据
        /// </summary>
        /// <param name="backgroundData">本底测量结果 [通道索引] = (α本底, β本底)</param>
        public void OnBackgroundMeasurementCompleted(Dictionary<int, (double alphaBackground, double betaBackground)> backgroundData)
        {
            try
            {
                // 保存本底数据到各通道配置
                foreach (var kvp in backgroundData)
                {
                    int channelIndex = kvp.Key;
                    var (alphaBackground, betaBackground) = kvp.Value;

                    if (channelIndex < channelCount)
                    {
                        var channelData = channelDataList[channelIndex];
                        channelData.WorkConditions.AlphaBackground = alphaBackground;
                        channelData.WorkConditions.BetaBackground = betaBackground;
                        channelData.LastModified = DateTime.Now;

                        // 保存本底测量结果
                        if (channelData.MeasurementResults == null)
                        {
                            channelData.MeasurementResults = new MeasurementResultData();
                        }

                        channelData.MeasurementResults.BackgroundMeasurement = new BackgroundMeasurementResult
                        {
                            AlphaBackground = alphaBackground,
                            BetaBackground = betaBackground,
                            MeasurementTime = DateTime.Now
                        };

                        // 保存到JSON文件
                        ChannelDataManager.SaveChannelData(channelIndex, channelData);

                        System.Diagnostics.Debug.WriteLine($"通道 {channelIndex + 1} 本底测量结果已保存：α={alphaBackground:F6} CPS, β={betaBackground:F6} CPS");
                    }
                }

                UIMessageBox.ShowSuccess($"本底测量完成，结果已保存到各通道配置中\n共处理 {backgroundData.Count} 个通道的数据");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"保存本底测量结果失败：{ex.Message}");
            }
        }


        /// <summary>
        /// 计算平均值并保存本底测量结果
        /// </summary>
        private void CalculateAndSaveBackgroundAverages()
        {
            try
            {
                DateTime measurementTime = DateTime.Now;
                double measurementDuration = GetMeasurementDuration();

                foreach (var kvp in measurementHistory)
                {
                    int channelIndex = kvp.Key;
                    var measurements = kvp.Value;

                    if (measurements.Count == 0 || channelIndex >= channelCount) continue;

                    // 计算平均值
                    double alphaAverage = measurements.Average(m => m.alpha);
                    double betaAverage = measurements.Average(m => m.beta);

                    // 计算标准差（用于评估测量稳定性）
                    double alphaStdDev = CalculateStandardDeviation(measurements.Select(m => m.alpha).ToArray());
                    double betaStdDev = CalculateStandardDeviation(measurements.Select(m => m.beta).ToArray());

                    // 验证数据有效性
                    bool isValid = ValidateBackgroundData(alphaAverage, betaAverage, alphaStdDev, betaStdDev);

                    // 加载通道数据
                    var channelData = ChannelDataManager.LoadChannelData(channelIndex);

                    // 保存到工作条件（供其他测量使用）
                    channelData.WorkConditions.AlphaBackground = alphaAverage;
                    channelData.WorkConditions.BetaBackground = betaAverage;
                    channelData.LastModified = DateTime.Now;

                    // 保存本底测量结果
                    if (channelData.MeasurementResults == null)
                    {
                        channelData.MeasurementResults = new MeasurementResultData();
                    }

                    channelData.MeasurementResults.BackgroundMeasurement = new BackgroundMeasurementResult
                    {
                        AlphaBackground = alphaAverage,
                        BetaBackground = betaAverage,
                        MeasurementTime = measurementTime,
                        MeasurementDuration = measurementDuration
                    };

                    // 使用Manager保存数据
                    bool saveSuccess = ChannelDataManager.SaveChannelData(channelIndex, channelData);

                    if (saveSuccess)
                    {
                        System.Diagnostics.Debug.WriteLine($"通道 {channelIndex + 1} 本底测量平均结果已保存：" +
                            $"α={alphaAverage:F6}±{alphaStdDev:F6} CPS, β={betaAverage:F6}±{betaStdDev:F6} CPS, " +
                            $"数据有效性：{(isValid ? "有效" : "异常")}");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"通道 {channelIndex + 1} 本底测量结果保存失败");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"计算和保存本底测量平均值失败: {ex.Message}");
                throw;
            }
        }


        /// <summary>
        /// 计算标准差
        /// </summary>
        private double CalculateStandardDeviation(double[] values)
        {
            if (values.Length <= 1) return 0;

            double mean = values.Average();
            double sumOfSquaredDifferences = values.Sum(val => (val - mean) * (val - mean));
            return Math.Sqrt(sumOfSquaredDifferences / (values.Length - 1));
        }

        /// <summary>
        /// 验证本底数据的有效性
        /// </summary>
        private bool ValidateBackgroundData(double alphaAverage, double betaAverage, double alphaStdDev, double betaStdDev)
        {
            // 检查平均值是否在合理范围内
            const double maxReasonableBackground = 1000; // CPS
            const double minBackground = 0;

            bool averageValid = alphaAverage >= minBackground && alphaAverage <= maxReasonableBackground &&
                               betaAverage >= minBackground && betaAverage <= maxReasonableBackground;

            // 检查标准差是否过大（相对标准差不应超过20%）
            bool stdDevValid = true;
            if (alphaAverage > 0)
            {
                double alphaRelativeStdDev = alphaStdDev / alphaAverage;
                stdDevValid &= alphaRelativeStdDev <= 0.2; // 20%
            }
            if (betaAverage > 0)
            {
                double betaRelativeStdDev = betaStdDev / betaAverage;
                stdDevValid &= betaRelativeStdDev <= 0.2; // 20%
            }

            return averageValid && stdDevValid;
        }

        /// <summary>
        /// 获取测量时长（分钟）
        /// </summary>
        private double GetMeasurementDuration()
        {
            try
            {
                if (txtMeasurementTime != null && double.TryParse(txtMeasurementTime.Text, out double duration))
                {
                    return duration;
                }
                return 5.0; // 默认5分钟
            }
            catch
            {
                return 5.0;
            }
        }

        /// <summary>
        /// 重置测量状态
        /// </summary>
        private void ResetMeasurementState()
        {
            currentMeasurementCycle = 0;
            totalMeasurementCycles = 0;
            measurementHistory.Clear();
        }

        #endregion
    }
}